package com.yc.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//和servlet一样，它也需要注解 名字，随意         value 那些内容需要过滤
@WebFilter(filterName="checkLoginFilter",value="/back/manager/*")
public class CheckLoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
			throws IOException, ServletException {
		//这个是我们的核心
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		//得到session
		HttpSession session = request.getSession();
		if( session.getAttribute("AdminUser")  == null){
			//意味着没有登录
			//跳转到登录界面
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			
			//得到绝对路径			http			://	 	localhost 		:	8080		/	snacknet	/
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
			out.print("<script>alert('请先登录！');location.href='"+basePath+"index.html';</script>");
			out.flush();
			out.close();
		}else{
			//登录了
			filterChain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
